#include "head_c.h"

int download(const user_t* status, const portocol_t* portocol, int socket_fd)
{
    int file_name_len = 0;
    char file_name[60] = {0};
    size_t file_size = 0;
    char ret[10] = {0};
    
    recv(socket_fd, ret, 1, MSG_WAITALL);
    //printf("gets.c: 11: %s\n",ret);
    if (strcmp(ret, "1") == 0)
    {
        printf("无此文件\n");
        return -1;
    }
    recv(socket_fd, &file_name_len, sizeof(int), MSG_WAITALL);
    //printf("gets.c: 18: %d\n", file_name_len);
    recv(socket_fd, file_name, file_name_len, MSG_WAITALL);
    //printf("gets.c: 20: %s\n", file_name);
    recv(socket_fd, &file_size, sizeof(size_t), MSG_WAITALL);
    //printf("gets.c: 22: %ld\n", file_size);
    
    int file_fd = open(file_name, O_RDWR | O_CREAT, 0666);
    //说明文件已存在
    //send(socket_fd, &file_fd, sizeof(int), MSG_NOSIGNAL);
    /*if (file_fd == -1)
    {
        
        int con_fd = open(file_name, O_RDWR);
        struct stat st;
        fstat(con_fd, &st);
        off_t curr_size = st.st_size;
        printf("curr_size = %ld\n", curr_size);
        lseek(con_fd, curr_size, SEEK_SET);
        send(socket_fd, &curr_size, sizeof(off_t), MSG_NOSIGNAL);
        off_t need_size = 0;
        recv(socket_fd, &need_size, sizeof(off_t), MSG_WAITALL);
        ftruncate(con_fd, file_size);
        char* p = (char*)mmap(NULL, need_size, PROT_READ | PROT_WRITE, MAP_SHARED, con_fd, 0);
        recv(socket_fd, p, need_size, MSG_WAITALL);
        munmap(p, need_size);
        printf("断点续传完成\n");
        close(con_fd);
        close(socket_fd);
        return 0;
    }*/
    ftruncate(file_fd, file_size);
    char* p = (char*)mmap(NULL, file_size, PROT_READ | PROT_WRITE, MAP_SHARED, file_fd, 0);
    int ret_size = recv(socket_fd, p, file_size, MSG_WAITALL);
    munmap(p, file_size);
    ftruncate(file_fd, ret_size);
    //printf("ret_size = %d", ret_size);
    printf("文件传输完成\n");

    close(file_fd);

    return 0;
}
